package com.lvcoding.codegen.controller;

import cn.hutool.core.util.StrUtil;
import com.lvcoding.codegen.domain.Db;
import com.lvcoding.codegen.domain.Res;
import com.lvcoding.codegen.domain.TableClass;
import com.lvcoding.codegen.utils.DbUtil;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @Description 描述
 * @Date 2020-12-30 1:33 下午
 * @Author wuyanshen
 */
@RestController
public class DbController {

    @PostMapping("/connect")
    public Res connect(@RequestBody Db db) {
        Connection connection = null;
        try {
            connection = DbUtil.initDb(db);
            if(connection != null) {
                return Res.success("数据库连接成功");
            } else {
                return Res.fail("数据库连接失败");
            }
        } catch (Exception e) {
            return Res.fail("数据库连接失败 " + e.getMessage());
        }

    }

    @PostMapping("/disconnect")
    public Res disconnect() {
        DbUtil.disconnect();
        return Res.success("断开数据库连接成功");
    }

    @PostMapping("/config")
    public Res config(@RequestBody Map<String,String> map) {
        try {
            String packageName = map.get("packageName");
            Connection connection = DbUtil.getConnection();
            DatabaseMetaData metaData = connection.getMetaData();
            ResultSet tables = metaData.getTables(connection.getCatalog(), null, null, null);
            List<TableClass> tableClassList = new ArrayList<>();
            while (tables.next()) {
                TableClass tableClass = new TableClass();
                String tableName = tables.getString("TABLE_NAME");
                tableClass.setTableName(tableName);
                String domainName = StrUtil.upperFirst(StrUtil.toCamelCase(tableName));
                tableClass.setDomainName(domainName);
                tableClass.setControllerName(domainName+"Controller");
                tableClass.setMapperName(domainName+"Mapper");
                tableClass.setServiceName(domainName+"Service");
                tableClass.setPackageName(packageName);
                tableClassList.add(tableClass);
            }
            return Res.success("数据库信息读取成功", tableClassList);
        }catch (Exception e) {
            e.printStackTrace();
        }
        return Res.fail("数据库信息读取失败");
    }
}
